package leetcode.code1801;

import java.util.PriorityQueue;

import leetcode.IDebug;

public class Solution implements IDebug {

	int mod = (int) 1e9 + 7;

	public int getNumberOfBacklogOrders(int[][] orders) {
		PriorityQueue<int[]> queueSell = new PriorityQueue<>((a, b) -> a[0] - b[0]);
		PriorityQueue<int[]> queueBuy = new PriorityQueue<>((a, b) -> b[0] - a[0]);
		int len = orders.length;
		for (int i = 0; i < len; i++) {
			int[] order = orders[i];
			int pricei = order[0], amounti = order[1], orderTypei = order[2];
			if (orderTypei == 0) {
				// buy
				while (!queueSell.isEmpty() && queueSell.peek()[0] <= pricei && amounti > 0) {
					int[] cur = queueSell.poll();
					int price = cur[0], amount = cur[1];
					int dif = Math.min(amounti, amount);
					amount -= dif;
					amounti -= dif;
					if (amount > 0) {
						queueSell.add(new int[] { price, amount });
					}
				}
				if (amounti > 0) {
					queueBuy.add(new int[] { pricei, amounti });
				}
			} else {
				// sell
				while (!queueBuy.isEmpty() && queueBuy.peek()[0] >= pricei && amounti > 0) {
					int[] cur = queueBuy.poll();
					int price = cur[0], amount = cur[1];
					int dif = Math.min(amounti, amount);
					amount -= dif;
					amounti -= dif;
					if (amount > 0) {
						queueBuy.add(new int[] { price, amount });
					}
				}
				if (amounti > 0) {
					queueSell.add(new int[] { pricei, amounti });
				}
			}
		}
		long ans = 0;
		while (!queueBuy.isEmpty()) {
			ans += queueBuy.poll()[1];
			ans %= mod;
		}
		while (!queueSell.isEmpty()) {
			ans += queueSell.poll()[1];
			ans %= mod;
		}
		return (int) ans;
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
